package com.xxg.renrenorder.service;

import com.alibaba.fastjson.JSON;
import com.xxg.renrencommon.api.UserManager;
import com.xxg.renrencommon.domain.bean.CarryProductInfo;
import com.xxg.renrencommon.domain.bean.Product;
import com.xxg.renrencommon.domain.constant.AccountConstant;
import com.xxg.renrencommon.domain.dao.RenrenShopGoods;
import com.xxg.renrencommon.domain.dao.RenrenShopGoodsOption;
import com.xxg.renrencommon.domain.dao.RenrenShopUser;
import com.xxg.renrencommon.domain.filedenum.accountenum.AccountGroupEnum;
import com.xxg.renrencommon.domain.filedenum.orderenum.OptTypeEnum;
import com.xxg.renrencommon.domain.filedenum.orderenum.OrderStatusEnum;
import com.xxg.renrencommon.domain.filedenum.orderenum.OrderTypeEnum;
import com.xxg.renrencommon.domain.result.BaseResult;
import com.xxg.renrencommon.domain.result.PageInfoResult;
import com.xxg.renrencommon.exception.OrderManagerException;
import com.xxg.renrencommon.exception.exceptionenum.OrderExceptionCodeCodeEnum;
import com.xxg.renrenorder.component.OrderComponent;
import com.xxg.renrenorder.component.ProductStockComponent;
import com.xxg.renrenorder.dao.*;
import com.xxg.renrenorder.dao.bean.*;
import com.xxg.renrenorder.domain.query.*;
import com.xxg.renrenorder.domain.result.OrderMasterInfoResult;
import com.xxg.renrenorder.domain.result.ReFundResult;
import com.xxg.renrenorder.message.DelayMessageSender;
import com.xxg.renrenorder.util.DateTimeUtil;
import com.xxg.renrenorder.util.OrderIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 类说明
 *
 * @author szj
 * @date 2021/12/7
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService{
    @Resource
    private OrderMasterInfoDao orderMasterInfoDao;
    @Resource
    private CommissionSettingInfoDao commissionSettingInfoDao;
    @Resource
    private AfterSalesOrderInfoDao afterSalesOrderInfoDao;
    @Resource
    private RenrenShopUserDao renrenShopUserDao;
    @Resource
    private RenrenShopGoodsOptionDao renrenShopGoodsOptionDao;
    @Resource
    private RenrenShopGoodsDao renrenShopGoodsDao;
    @Resource
    private RenrenShopShopDao renrenShopShopDao;
    @Resource
    private CarryProductInfoDao carryProductInfoDao;
    @Resource
    private UserCartInfoDao userCartInfoDao;
    @Resource
    private ProductStockComponent productStockComponent;
    @Resource
    private DelayMessageSender delayMessageSender;
    @Resource
    private OrderIdGenerator orderIdGenerator;
    @Resource
    private OrderComponent orderComponent;
    @DubboReference(version = "1.0.0")
    private UserManager userManager;

    @Override
    public BaseResult<List<OrderMasterInfo>> getOrdersByStatus(String userId, Integer orderStatus, Integer pageNo, Integer pageSize) {
        List<OrderMasterInfo> list = orderMasterInfoDao.getOrdersByUserId(Integer.parseInt(userId), orderStatus,
                pageNo - 1, pageSize);
        return new BaseResult<>(list);
    }

    @Override
    public BaseResult<PageInfoResult<OrderMasterInfo>> getAllOrdersByStatus(List<Integer> orderStatus, Integer pageNo, Integer pageSize, String startDate, String endDate, OrderListQuery orderListQuery, String shopId, String account) {
        Date[] dates;
        try {
            dates = DateTimeUtil.convertDate(startDate, endDate);
        } catch (OrderManagerException e) {
            return new BaseResult<>(OrderExceptionCodeCodeEnum.INVALID_PARAMETER, e.getMessage(), null);
        }
        List<OrderMasterInfo> list;
        long total;
        if (AccountConstant.matchAdmin(account)) {
            list = orderMasterInfoDao.getAllOrdersByStatus(orderStatus, pageNo - 1, pageSize, dates, orderListQuery, null);
            total = orderMasterInfoDao.countAllOrdersByStatus(orderStatus, dates, orderListQuery, null);
        }else {
            list = orderMasterInfoDao.getAllOrdersByStatus(orderStatus, pageNo - 1, pageSize, dates, orderListQuery, Integer.parseInt(shopId));
            total = orderMasterInfoDao.countAllOrdersByStatus(orderStatus, dates, orderListQuery, Integer.parseInt(shopId));
        }
        PageInfoResult<OrderMasterInfo> pageInfoResult = new PageInfoResult<>(total, list);
        return new BaseResult<>(pageInfoResult);
    }

    @Override
    public BaseResult<OrderMasterInfo> settleAccounts(String userId, SettleAccountsQuery query) {
        int userIdInt = Integer.parseInt(userId);
        RenrenShopUser renrenShopUser = renrenShopUserDao.selectNormalByPrimaryKey(userIdInt);
        if (renrenShopUser == null) {
            return new BaseResult<>(OrderExceptionCodeCodeEnum.NO_USER_OR_USER_ILLEGAL);
        }
        Integer groupId = renrenShopUser.getGroupId();
        if (AccountGroupEnum.FACTORY.match(groupId)) {
            return new BaseResult<>(OrderExceptionCodeCodeEnum.FACTORY_USER_CAN_NOT_BUY);
        }
        CommissionInfo commissionInfo = getCommissionInfo(groupId);
        OrderMasterInfo orderMasterInfo = new OrderMasterInfo();
        orderMasterInfo.setCommissionInfo(commissionInfo);
        orderMasterInfo.setAddressInfo(getUserAddress(userId));
        return new BaseResult<>(orderMasterInfo);
    }

    private CommissionInfo getCommissionInfo(Integer groupId) {
        CommissionSettingInfo settingInfo = commissionSettingInfoDao.findByGroupId(groupId);
        CommissionInfo commissionInfo = new CommissionInfo();
        commissionInfo.setDescription("服务费");
        if (settingInfo == null) {
            commissionInfo.setRatio("0");
        }else {
            commissionInfo.setRatio(settingInfo.getRatio());
        }
        return commissionInfo;
    }

    @Override
    public BaseResult<Void> finishAfterSalesOrder(String id, ReFundResult response) {
        log.info("finishAfterSalesOrder id:{}, response:{}", id, JSON.toJSONString(response));
        AfterSalesOrderInfo order = afterSalesOrderInfoDao.finishAfterSalesOrder(id, response);
        if (order != null) {
            // 修改原定单中商品的returnNumber,applyNumber
            orderMasterInfoDao.updateProductReturnNumber(order.getOrderId(), order.getProductInfo().getSkuId(),
                    0, order.getNumber());
        }
        return new BaseResult<>();
    }

    @Override
    public BaseResult<String> submitOrder(String userId, SubmitOrderQuery query) {
        int userIdInt = Integer.parseInt(userId);
        RenrenShopUser renrenShopUser = renrenShopUserDao.selectNormalByPrimaryKey(userIdInt);
        if (renrenShopUser == null) {
            return new BaseResult<>(OrderExceptionCodeCodeEnum.NO_USER_OR_USER_ILLEGAL);
        }
        if (AccountGroupEnum.FACTORY.match(renrenShopUser.getGroupId())) {
            return new BaseResult<>(OrderExceptionCodeCodeEnum.FACTORY_USER_CAN_NOT_BUY);
        }
        List<SubmitProductAccount> productAccounts = query.getProductAccounts();
        List<Integer> spuIds = productAccounts.stream().map(SubmitProductAccount::getSpuId).distinct().collect(Collectors.toList());
        List<RenrenShopShop> renrenShopShops = renrenShopShopDao.selectByGoodsIds(spuIds);
        Map<Integer, RenrenShopShop> shopMap = new HashMap<>(renrenShopShops.size());
        renrenShopShops.forEach(renrenShopShop -> {
            if (!shopMap.containsKey(renrenShopShop.getId())) {
                shopMap.put(renrenShopShop.getId(), renrenShopShop);
            }
        });
        // 检验商品参数（商品状态，店铺状态）
        List<Product> products = null;
        try {
            products = getProducts(spuIds, shopMap);
        } catch (OrderManagerException e) {
            log.error(e.getErrorMessage(), e);
            return new BaseResult<>(e);
        }
        int orderType = OrderTypeEnum.NORMAL.getValue();
        BigDecimal totalPrice = new BigDecimal("0");
        BigDecimal total = new BigDecimal("0");
        // 组装商品信息
        List<ProductInfo> productInfos = new ArrayList<>(products.size());
        Map<String, Product> productMap = products.stream().collect(Collectors.toMap(Product::getId, product -> product));
        for (SubmitProductAccount productAccount : productAccounts) {
            String tempId = productAccount.getSpuId() + "_" + productAccount.getSkuId();
            Product product = productMap.get(tempId);
            if (product == null) {
                return new BaseResult<>(OrderExceptionCodeCodeEnum.GOODS_ILLEGAL, productAccount.getSkuName() + "_" + OrderExceptionCodeCodeEnum.GOODS_ILLEGAL.getName(), null);
            }
            if (product.getSpuStock() < productAccount.getQuantity()) {
                return new BaseResult<>(OrderExceptionCodeCodeEnum.GOODS_STOCK_NOT_ENOUGH, productAccount.getSkuName() + "_" + OrderExceptionCodeCodeEnum.GOODS_STOCK_NOT_ENOUGH.getName(), null);
            }
            ProductInfo productInfo = new ProductInfo();
            productInfo.setIsCarryProduct(false);
            CarryProductInfo carryProductInfo = carryProductInfoDao.findByCarrySpuId(product.getSpuId());
            if (carryProductInfo != null) {
                Map<String, Integer> skuIdMap = carryProductInfo.getSkuIdMap();
                if (skuIdMap != null && skuIdMap.size() > 0) {
                    boolean b = skuIdMap.containsKey(String.valueOf(product.getSkuId()));
                    if (b) {
                        // 映射包含，查看被带货商品是否存在
                        orderType = OrderTypeEnum.CARRY.getValue();
                        productInfo.setIsCarryProduct(true);
                    }
                }
            }
            BeanUtils.copyProperties(product, productInfo);
            productInfo.setNumber(productAccount.getQuantity());
            productInfo.setPay(product.getSkuPrice());
            productInfo.setRemark(productAccount.getRemark());
            productInfos.add(productInfo);
            totalPrice = totalPrice.add(product.getSkuPrice().multiply(new BigDecimal(productInfo.getNumber())));
            total = total.add(productInfo.getPay().multiply(new BigDecimal(productInfo.getNumber())));
        }
        // 生成订单ID
        long orderId = orderIdGenerator.createId();
        productInfos.stream().map(ProductInfo::getShopId).distinct();
        List<ProductInfo> productInfoList = productInfos.stream().filter(productInfo -> !productInfo.getIsCarryProduct()).collect(Collectors.toList());
        // 更新非带货商品的库存和销量
        try {
            productStockComponent.updateStockAndSales(productInfoList);
        } catch (OrderManagerException e) {
            return new BaseResult<>(e);
        }
        try {
            submitOrder(query, userIdInt, renrenShopUser.getGroupId(), orderType, totalPrice, total, productInfos, orderId);
        } catch (Exception e) {
            log.error("提交失败_" + e.getMessage(), e);
            try {
                productStockComponent.rollBackStockAndSales(productInfoList);
            } catch (Exception exception) {
                log.error("回滚失败_" + e.getMessage(), e);
                log.info("回滚数据:{}", JSON.toJSONString(productInfos));
            }
            return new BaseResult<>(OrderExceptionCodeCodeEnum.SUBMIT_ORDER_ERROR);
        }
        return new BaseResult<>(String.valueOf(orderId));
    }

    @Override
    public boolean cancelOrderById(String id) {
        int count = orderMasterInfoDao.cancelOrderById(id);
        // 取消订单后，需要归还库存
        if (count > 0) {
            OrderMasterInfo orderMasterInfo = orderMasterInfoDao.getOrderByOrderId(id);
            productStockComponent.rollBackStockAndSales(orderMasterInfo.getProductInfos());
            orderComponent.recordOpt(id, 0, OptTypeEnum.CANCEL_ORDER);
            return true;
        }
        return false;
    }

    @Override
    public BaseResult<Void> cancelOrderById(String id, String userIdStr) {
        int userId = Integer.parseInt(userIdStr);
        int count = orderMasterInfoDao.cancelOrderById(id, userId);
        // 取消订单后，需要归还库存
        if (count > 0) {
            OrderMasterInfo orderMasterInfo = orderMasterInfoDao.getOrderByOrderId(id);
            productStockComponent.rollBackStockAndSales(orderMasterInfo.getProductInfos());
            orderComponent.recordOpt(id, userId, OptTypeEnum.CANCEL_ORDER);
        }
        return new BaseResult<>();
    }

    @Override
    public BaseResult<Void> commitOrderById(String id, String userId, String shopId, String account) {
        if (AccountConstant.matchAdmin(account)) {
            orderMasterInfoDao.commitOrderById(id, null);
        }else {
            orderMasterInfoDao.commitOrderById(id, Integer.parseInt(shopId));
        }
        // 发送15天支付倒计时消息和30天倒计时消息
        OrderMsg orderMsg = new OrderMsg();
        orderMsg.setId(id);
        delayMessageSender.sendMsgB(orderMsg);
        if (userId != null) {
            orderComponent.recordOpt(id, Integer.parseInt(userId), OptTypeEnum.CONFIRM);
        }
        return new BaseResult<>();
    }

    @Override
    public boolean autoCommitOrder(String id) {
        OrderMasterInfo orderMasterInfo = orderMasterInfoDao.getOrderByOrderId(id);
        if (orderMasterInfo != null) {
            // 未确认收货，则自动确认
            if (orderMasterInfo.getDoneTime() == null) {
                commitOrderById(id, null, null, null);
                orderComponent.recordOpt(id, 0, OptTypeEnum.CONFIRM);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean autoDisableOrderAfterService(String id) {
        // 关闭售后标志
        orderMasterInfoDao.closeAfterSales(id);
        orderComponent.recordOpt(id, 0, OptTypeEnum.AFTER_SALE_CLOSE);
        return true;
    }

    @Override
    public BaseResult<Void> setOneOrderExpress(SetOneOrderExpressQuery query, String userIdStr, String shopIdStr, String account) {
        final Integer userId = Integer.parseInt(userIdStr);
        final Integer shopId = Integer.parseInt(shopIdStr);
        final String orderId = query.getId();
        OrderMasterInfo order = orderMasterInfoDao.getOrderByOrderId(orderId);
        if (OrderTypeEnum.CARRY.match(order.getOrderType())) {
            if (query.getIsCarryBySelf() == null) {
                return new BaseResult<>(OrderExceptionCodeCodeEnum.CARRY_ORDER_NEED_CHOOSE_CARRY_BY_SELF);
            }else if (!query.getIsCarryBySelf()) {
                // 生成一份订单给上家
                List<ProductInfo> productInfos = order.getProductInfos();
                List<ProductInfo> collect = productInfos.stream().filter(ProductInfo::getIsCarryProduct).collect(Collectors.toList());
                List<SubmitProductAccount> productAccounts = new ArrayList<>(collect.size());
                List<Integer> goodsIds = new ArrayList<>(collect.size());
                collect.forEach(v -> {
                    CarryProductInfo carryProductInfo = carryProductInfoDao.findByCarrySpuId(v.getSpuId());
                    Map<String, Integer> skuIdMap = carryProductInfo.getSkuIdMap();
                    SubmitProductAccount submitProductAccount = new SubmitProductAccount();
                    submitProductAccount.setSpuId(carryProductInfo.getSpuId());
                    if (!v.getSkuId().equals(v.getSpuId())) {
                        submitProductAccount.setSkuId(skuIdMap.get(String.valueOf(v.getSkuId())));
                    }else {
                        submitProductAccount.setSkuId(carryProductInfo.getSpuId());
                    }
                    submitProductAccount.setQuantity(v.getNumber());
                    submitProductAccount.setSkuName(v.getSkuName());
                    goodsIds.add(carryProductInfo.getSpuId());
                });
                Integer shopId1 = order.getShopId();
                RenrenShopShop renrenShopShop = renrenShopShopDao.selectByPrimaryKey(shopId1);
                SubmitOrderQuery submitOrderQuery = new SubmitOrderQuery();
                submitOrderQuery.setProductAccounts(productAccounts);
                submitOrderQuery.setRemark("系统下单");
                submitOrderQuery.setAddressInfo(getUserAddress(String.valueOf(renrenShopShop.getUserId())));
                BaseResult<String> result = submitOrder(String.valueOf(renrenShopShop.getUserId()), submitOrderQuery);
                if (result.getCode() != 200) {
                    return new BaseResult<>(result.getCode(), result.getMessage(), result.getErrorMessage(), null);
                }else {
                    // 更新带货商品底下所有的库存和销量
                    productStockComponent.updateCarryProductStockAndSales(goodsIds);
                }
            }
        }
        if (AccountConstant.matchAdmin(account)) {
            orderMasterInfoDao.setOneOrderExpress(orderId, query.getExpCode(), query.getExpNo(), query.getExpImage(), query.getRemark(), null);
        }else {
            orderMasterInfoDao.setOneOrderExpress(orderId, query.getExpCode(), query.getExpNo(), query.getExpImage(), query.getRemark(), shopId);
        }
        OrderMsg orderMsg = new OrderMsg();
        orderMsg.setId(orderId);
        delayMessageSender.sendMsgA(orderMsg);
        delayMessageSender.sendMsgC(orderMsg);
        orderComponent.recordOpt(orderId, userId, OptTypeEnum.EXPRESS);
        return new BaseResult<>();
    }

    @Override
    public BaseResult<Void> updateCarryProduct(UpdateCarryProductQuery query) {
        if (!query.checkPassword()) {
            return new BaseResult<>();
        }
        ArrayList<Integer> list = new ArrayList<>();
        list.add(query.getSpuId());
        productStockComponent.updateCarryProductStockAndSales(list);
        return new BaseResult<>();
    }

    @Override
    public BaseResult<OrderMasterInfoResult> getOrderById(String id, String userId) {
        OrderMasterInfo orderMasterInfo = orderMasterInfoDao.getOrderByOrderId(id);
        OrderMasterInfoResult orderMasterInfoResult = new OrderMasterInfoResult();
        BeanUtils.copyProperties(orderMasterInfo, orderMasterInfoResult);
        orderMasterInfoResult.setIsSelf(userId.equals(String.valueOf(orderMasterInfo.getUserId())));
        return new BaseResult<>(orderMasterInfoResult);
    }

    @Override
    public BaseResult<Void> removeOrderById(String id, String userId) {
        orderMasterInfoDao.removeOrderByIdUserId(id, Integer.parseInt(userId));
        return new BaseResult<>();
    }

    public void submitOrder(SubmitOrderQuery query, int userIdInt, int userGroupId, int orderType, BigDecimal totalPrice, BigDecimal total, List<ProductInfo> productInfos, Long orderId) {
        // 提交订单
        OrderMasterInfo orderMasterInfo = new OrderMasterInfo();
        orderMasterInfo.setId(String.valueOf(orderId));
        orderMasterInfo.setUserId(userIdInt);
        orderMasterInfo.setUserGroupId(userGroupId);
        orderMasterInfo.setAddressInfo(query.getAddressInfo());
        orderMasterInfo.setOrderStatus(OrderStatusEnum.UN_PAID.getValue());
        orderMasterInfo.setDeleted(false);
        orderMasterInfo.setProductInfos(productInfos);
        orderMasterInfo.setTotal(total.setScale(2, BigDecimal.ROUND_HALF_UP));
        orderMasterInfo.setTotalPrice(totalPrice.setScale(2, BigDecimal.ROUND_HALF_UP));
        orderMasterInfo.setTotalDiscount(new BigDecimal("0"));
        CommissionInfo commissionInfo = getCommissionInfo(userGroupId);
        orderMasterInfo.setCommissionInfo(commissionInfo);
        orderMasterInfo.setCommission(new BigDecimal("0"));
        if (AccountGroupEnum.STORE.match(userGroupId) || AccountGroupEnum.SUPPER_DEALER.match(userGroupId)) {
            orderMasterInfo.setCommission(orderMasterInfo.getTotal().multiply(new BigDecimal(commissionInfo.getRatio())));
        }
        orderMasterInfo.setTotalPay(orderMasterInfo.getTotal().subtract(orderMasterInfo.getTotalDiscount()).add(orderMasterInfo.getCommission()));
        orderMasterInfo.setTotalCouponDiscount(new BigDecimal("0"));
        orderMasterInfo.setExpressFee(new BigDecimal("0"));
        orderMasterInfo.setExpressType(1);
        orderMasterInfo.setRemark(query.getRemark());
        orderMasterInfo.setOrderType(orderType);
        orderMasterInfoDao.submitOrder(orderMasterInfo);
        // 发送30M支付倒计时消息
        OrderMsg orderMsg = new OrderMsg();
        orderMsg.setId(orderMasterInfo.getId());
        delayMessageSender.sendMsg(orderMsg);
        try {
            // 清空购物车对应数据
            if (query.getUserCartIds() != null && query.getUserCartIds().size() > 0) {
                userCartInfoDao.removeProductFromCart(userIdInt, query.getUserCartIds());
            }
        } catch (Exception e) {
            log.error("清空购物车对应数据_" + e.getMessage(), e);
        }
    }

    /**
     * 获取用户地址
     *
     * @param userId 会员ID
     * @return 地址
     */
    private AddressInfo getUserAddress(String userId) {
        List<String> address = userManager.getUserDefaultAddress(userId);
        if (address == null) {
            return null;
        }
        AddressInfo addressInfo = new AddressInfo();
        addressInfo.setName(address.get(0));
        addressInfo.setPhone(address.get(1));
        addressInfo.setAddress(address.get(2));
        addressInfo.setAreaCode(Integer.parseInt(address.get(4)));
        return addressInfo;
    }

    /**
     * 查询商品信息
     *
     * @param ids ID列表
     * @return 结果
     */
    private List<Product> getProducts(List<Integer> ids, Map<Integer, RenrenShopShop> shopMap) throws OrderManagerException {
        List<Product> list = new LinkedList<>();
        List<RenrenShopGoods> shopGoods = renrenShopGoodsDao.selectByIds(ids);
        List<RenrenShopGoodsOption> goodsOptions = renrenShopGoodsOptionDao.selectByGoodsIds(ids);
        Map<Integer, List<RenrenShopGoodsOption>> optionsMap = skuGroupBySpuId(shopGoods.size(), goodsOptions);
        for (RenrenShopGoods e : shopGoods) {
            if (e.getHasOption()) {
                // 多规格商品
                if (optionsMap.containsKey(e.getId())) {
                    List<RenrenShopGoodsOption> options = optionsMap.get(e.getId());
                    list.addAll(goodOption2Product(e, options, shopMap));
                }
            } else {
                // 单规格商品
                list.add(good2Product(e, shopMap));
            }
        }
        return list;
    }

    /**
     * 多规格商品分组
     *
     * @param goodsOptions 多规格商品信息
     * @return 结果
     */
    private Map<Integer, List<RenrenShopGoodsOption>> skuGroupBySpuId(int size, List<RenrenShopGoodsOption> goodsOptions) {
        // 多规格商品SKU处理
        Map<Integer, List<RenrenShopGoodsOption>> optionsMap = new HashMap<>(size * 4 / 3 + 1);
        goodsOptions.forEach(e -> {
            if (!optionsMap.containsKey(e.getGoodsId())) {
                optionsMap.put(e.getGoodsId(), new LinkedList<>());
            }
            optionsMap.get(e.getGoodsId()).add(e);
        });
        return optionsMap;
    }

    /**
     * 多规格商品转SKU
     *
     * @param good    SPU
     * @param options 多规格
     * @return 结果
     */
    public List<Product> goodOption2Product(RenrenShopGoods good, List<RenrenShopGoodsOption> options, Map<Integer, RenrenShopShop> shopMap) throws OrderManagerException{
        List<Product> products = new ArrayList<>(options.size());
        BigDecimal minCostPrice = new BigDecimal("0");
        BigDecimal maxCostPrice = new BigDecimal("0");
        for (RenrenShopGoodsOption sku : options) {
            String id = good.getId() + "_" + sku.getId();
            RenrenShopShop renrenShopShop = shopMap.get(good.getShopId());
            if (renrenShopShop == null) {
                throw new OrderManagerException(good.getTitle() + "_" + OrderExceptionCodeCodeEnum.GOODS_UNDER_ILLEGAL_SHOP.getName(), OrderExceptionCodeCodeEnum.GOODS_UNDER_ILLEGAL_SHOP.getCode());
            }
            String shopName = renrenShopShop.getName();
            String skuName = good.getTitle() + "|" + sku.getTitle();
            Product product = new Product(id, good.getId(), sku.getId(), good.getShopId(), shopName, good.getTitle(),
                    skuName, good.getSubTitle(), good.getShortTitle(), good.getType(), good.getThumb(),
                    good.getThumbAll(), good.getVideo(), good.getVideoThumb(), good.getVideoType(), sku.getStock(),
                    good.getSales(), good.getRealSales(), good.getContent(), good.getIsRecommand(), good.getIsHot(),
                    good.getIsNew(), sku.getPrice(), good.getMinPrice(), good.getMaxPrice(), good.getCostPrice(),
                    good.getCostPrice(), sku.getCostPrice(), sku.getOriginalPrice(), sku.getSales(), sku.getThumb(),
                    null, good.getStatus(), good.getIsDeleted());
            products.add(product);
            if (minCostPrice.compareTo(sku.getCostPrice()) > 0) {
                minCostPrice = sku.getCostPrice();
            }
            if (maxCostPrice.compareTo(sku.getCostPrice()) < 0) {
                maxCostPrice = sku.getCostPrice();
            }
        }
        for (Product p : products) {
            p.setSpuMinCostPrice(minCostPrice);
            p.setSpuMaxCostPrice(maxCostPrice);
        }
        return products;
    }

    /**
     * 单规格商品转sku
     *
     * @param good SPU
     * @return 结果
     */
    public Product good2Product(RenrenShopGoods good, Map<Integer, RenrenShopShop> shopMap) throws OrderManagerException {
        String id = good.getId() + "_" + good.getId();
        RenrenShopShop renrenShopShop = shopMap.get(good.getShopId());
        if (renrenShopShop == null) {
            throw new OrderManagerException(good.getTitle() + "_" + OrderExceptionCodeCodeEnum.GOODS_UNDER_ILLEGAL_SHOP.getName(), OrderExceptionCodeCodeEnum.GOODS_UNDER_ILLEGAL_SHOP.getCode());
        }
        String shopName = renrenShopShop.getName();
        return new Product(id, good.getId(), good.getId(), good.getShopId(), shopName, good.getTitle(),
                good.getTitle(), good.getSubTitle(), good.getShortTitle(), good.getType(), good.getThumb(),
                good.getThumbAll(), good.getVideo(), good.getVideoThumb(), good.getVideoType(), good.getStock(),
                good.getSales(), good.getRealSales(), good.getContent(), good.getIsRecommand(), good.getIsHot(),
                good.getIsNew(), good.getPrice(), good.getMinPrice(), good.getMaxPrice(), good.getCostPrice(),
                good.getCostPrice(), good.getCostPrice(), good.getOriginalPrice(), good.getSales(), null,
                null, good.getStatus(), good.getIsDeleted());
    }
}
